package com.zyj.core.builder;

import com.zyj.core.config.Configuration;
import com.zyj.core.factory.DefaultSqlSessionFactory;
import com.zyj.core.factory.SqlSessionFactory;
import com.zyj.core.utils.DocumentUtils;
import org.dom4j.Document;

import java.io.InputStream;
import java.io.Reader;

public class SqlSessionFactoryBuilder {

    /**
     * 工厂构建器的构建方法其实做的就是解析所有xml配置文件并且将得到的configuration对象让工厂所持有
     *
     * @param inputStream
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream) {

        // 获取配置文件对应的Document对象
        Document document = DocumentUtils.createDocument(inputStream);

        // 通过字节流封装Configuration
        // XMLConfigBuilder持有全局配置对象
        XMLConfigBuilder configBuilder = new XMLConfigBuilder();
        Configuration configuration = configBuilder.parseCofiguration(document.getRootElement());

        // 将解析出来的configuration对象给SqlSessionFactory持有
        return build(configuration);
    }

    public SqlSessionFactory build(Reader reader) {
        // 通过字符流封装Configuration
        Configuration configuration = null;
        return build(configuration);
    }

    private SqlSessionFactory build(Configuration configuration) {

        return new DefaultSqlSessionFactory(configuration);
    }

}
